<template>
  <div>
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @focus="isResultShow = false"
        @cancel="onCancel"
      />
    </form>
    <!-- 标准写法 -->
    <!-- <search-result v-if="isResultShow"></search-result>
    <template v-else> -->
    <!-- 搜索建议 -->
    <!-- <search-suggestion v-if="searchText"></search-suggestion> -->
    <!-- 搜索历史 -->
    <!-- <search-history v-else></search-history> -->
    <!-- </template> -->
    <!-- 搜索列表 -->
    <search-result v-if="isResultShow" :search-text="searchText">
      <!-- 把搜索的内容传到兄弟组件  -->
    </search-result>
    <!-- 搜索建议 -->
    <!-- 父组件传搜索内容 -->
    <search-suggest
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    >
      <!-- 父组件监听消息，打开搜索结果 -->
    </search-suggest>
    <!-- 搜索历史 -->
    <search-histroy
      :SearchHistories="SearchHistories"
      @clear="SearchHistories = []"
      v-else
    >
    </search-histroy>
  </div>
</template>

<script>
import { getItem, setItem } from '@/utils/storage'
// import { Toast } from 'vant'
import SearchHistroy from './components/search_histroy.vue'
import SearchResult from './components/search_result.vue'
import SearchSuggest from './components/search_suggest.vue'
export default {
  name: 'SearchPage',
  components: {
    SearchHistroy,
    SearchResult,
    SearchSuggest
  },
  data () {
    return {
      searchText: '', // 搜索内容
      isResultShow: false, // 是否搜索结果显示,
      SearchHistories: getItem('SearchHistories') || []
    }
  },
  created () {

  },
  mounted () {

  },
  methods: {
    onSearch (val) {
      // 保存点击的搜索内容
      this.searchText = val
      const i = this.SearchHistories.findIndex(t => t === val)
      if (i > -1) this.SearchHistories.splice(i, 1)
      this.SearchHistories.unshift(val)
      this.isResultShow = true
    },
    onCancel () {
    }
  },
  watch: {
    SearchHistories (val) {
      setItem('SearchHistories', val)
    }
  }
}
</script>

<style lang="less" scoped>
.van-search__action {
  color: #fff;
}
</style>